package java

import (
	"unicode/utf16"

	"gitee.com/microwww/jvm-go/jvm/class"
)

// 字符串 池
var internedStrings = map[string]*class.Object{}

func NewString(loader *class.ClassLoader, val string) *class.Object {
	js := internedStrings[val]
	if js == nil {
		clazz := loader.DefineClass("java/lang/String")
		u32 := []rune(val) // utf32
		u16 := utf16.Encode(u32)
		js = class.NewObject(clazz)
		ccz := loader.DefineClass("[C")
		chars := class.NewObject(ccz)
		chars.SetData(u16)
		js.SetFields("value", chars)
		internedStrings[val] = js
	}
	return js
}
